define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'jstree'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            $(document).on('click', '.percom-shop-type-item', function(){
                location.href = $(this).data('url');
            });
            //选择要铺设的商家
            $(document).on("click", ".btn-resubmit", function () {
                var ids = Table.api.selectedids(table);
                //alert(ids);
                Fast.api.open("performance/percom/resubmit/ids/" + ids, __('选择铺设商家'), {
                    area: ['800px', '500px'],
                    shadeClose:true,
                    shade:0.5,
                });
            });
            //方案使用门店
            $(document).on("click", ".useShop", function(){
                var id = $(this).data('id');
                Fast.api.open("performance/percom/use_shop/id/"+id, __('使用门店'), {
                    area: ['800px', '500px'],
                    shadeClose:true,
                    shade:0.5,
                });
            });
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'performance/percom/index' + location.search,
                    add_url: 'performance/percom/add',
                    edit_url: 'performance/percom/edit',
                    del_url: 'performance/percom/del',
                    multi_url: 'performance/percom/multi',
                    import_url: 'performance/percom/import',
                    table: 'percom',
                }
            });

            var table = $("#table");
            $(".btn-add").data("area", ["100%", "100%"]);

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });


            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                Search: true,
                commonSearch: true,
                searchFormVisible: true,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id'), operate: false },
                        { field: 'name', title: __('Name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'type', title: __('Type'), operate: false, searchList: { "0": __('Type 0'), "1": __('Type 1'), "2": __('Type 2') }, formatter: Table.api.formatter.normal },
                        {field: 'use_shop_count',title: __('使用门店数'),operate: false, formatter:function(value, row, index){
                            /*console.log(value);
                            console.log(row);
                            console.log(index);*/
                            return '<a href="javascript:" class="useShop" data-id="'+row.id+'">'+value+'</a>';
                        }},
                        {field: 'admin_username',title: __('操作人员'),operate: false},
                        { field: 'createtime', title: __('Createtime'), operate: false, addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'status', title: __('Status'), searchList: { "0": __('Status 0'), "1": __('Status 1') }, formatter: Table.api.formatter.status, custom:{0:'success', 1:'primary'} },
                        // {field: 'shop_id', title: __('Shop_id')},
                        //{ field: 'staff_ids', title: __('Staff_ids'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        // {field: 'status', title: __('Status'), searchList: {"0":__('Status 0'),"1":__('Status 1')}, formatter: Table.api.formatter.status},
                        // {field: 'gtype', title: __('Gtype'), searchList: {"0":__('Gtype 0'),"1":__('Gtype 1')}, formatter: Table.api.formatter.normal},
                        // {field: 'i1type', title: __('I1type'), searchList: {"0":__('I1type 0'),"1":__('I1type 1')}, formatter: Table.api.formatter.normal},
                        // {field: 'i3type', title: __('I3type'), searchList: {"0":__('I3type 0'),"1":__('I3type 1')}, formatter: Table.api.formatter.normal},
                        // {field: 'sku_ids', title: __('Sku_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'sku1_ids', title: __('Sku1_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'i3typesum', title: __('I3typesum'), operate: 'LIKE'},
                        // {field: 'i1typesum', title: __('I1typesum'), operate: 'LIKE'},
                        // {field: 'gtypesum', title: __('Gtypesum'), operate: 'LIKE'},

                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        //{ field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons :[
                                {
                                    name: 'resubmit',
                                    text: '铺设',
                                    title: '选择铺设商家',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\' data-shadeClose=true data-shade=0.5',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: "performance/percom/resubmit",
                                    hidden:function(row){
                                        if(row.show_copy == 0){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                }
                            ],
                            callback: function (data) {
                                table.bootstrapTable('refresh', {});
                                return false;
                            },
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'performance/percom/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'name', title: __('Name'), align: 'left' },
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'performance/percom/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'performance/percom/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
            $('.radio-ipt').on('change', function () {
                console.log();
                const nextScale = $(this).closest('.form-group').next('.form-group').find('.scale-ipt span')
                if ($(this).val() == '0') {
                    nextScale.text('%')
                } else {
                    nextScale.text('元')
                }
            })
            $(document).on('change', '.select-change', function () {
                console.log($(this).val());
                
                const nextScale = $(this).closest('.scale').next('div').find('.scale-ipt span')
                if ($(this).val() == '0') {
                    nextScale.text('%')
                } else {
                    nextScale.text('元')
                }
            })
            $('.select-change').on('change', function () {
                console.log($(this).val());
                
                const nextScale = $(this).closest('.scale').next('div').find('.scale-ipt span')
                if ($(this).val() == '0') {
                    nextScale.text('%')
                } else {
                    nextScale.text('元')
                }
            })


            $('.next-btn').click(function () {
                if ($('#c-name').val() == '') {
                    return layer.msg('请输入方案名称')
                }
                $('.basic-box').hide()
                $('.yuan-box').eq(1).addClass('yuan-active')
                $('.heng').addClass('heng-active')
                $('.scheme-box').show()
                /*if ($('#c-type').val() == 0) {
                    $('.title1').html(`<div></div>
                        普通商品 <span>默认针对所有商品生效</span>`)
                    $('.title2').html(` <div></div>
                        卡项商品 <span>默认针对所有商品生效</span>`)
                    $('.title3').html(` 次卡`)
                    $('.title4').html(`  充值卡`)
                    $(`.sale-box0`).show()
                    $(`.sale-box2`).remove()
                } else if ($('#c-type').val() == 1) {
                    $('.title1').html(` <div></div>
                        单项服务 <span>默认针对所有商品生效</span>`)
                    $('.title2').html(` <div></div>
                        消耗服务 <span>默认针对所有商品生效</span>`)
                    $('.title3').html(`  次卡 <span>单次费用基数按照售卡金额均排，如:次卡售卡金额1980元10次，则单次费用为1980/10=198元按百分比按固定金额</span>`)
                    $('.title4').html(`  充值卡 <span>单次费用基数按单次实际扣除金额计算</span>`)
                    $(`.sale-box0`).show()
                    $(`.sale-box2`).remove()
                } else {
                    $(`.sale-box0`).remove()
                    $(`.sale-box2`).show()
                }*/


            });
            //提成条件筛选
            $('.scheme-box .checkbox input[type="checkbox"]').click(function(){
                let that = $(this);
                switch(that.val())
                {
                    //职称
                    case '2':
                        if(that.is(':checked') == true)
                        {
                            //$('.scheme-box .body .zhicheng').show();
                            //选中
                            //追加表头
                            $('.scheme-box .body table thead tr th:eq(0)').after('<th style="width:80px;" class="zhicheng">员工职称</th>');
                            //获取tr
                            $('.scheme-box .body table tbody tr').each(function(index){
                                //获取当前所在行下第一个td是什么类型
                                var theTr = $(this);
                                switch(theTr.find('td:eq(0)').data('type'))
                                {
                                    //项目完整行
                                    case 'xiangmu':
                                        theTr.find('td:eq(0)').after('<td data-type="zhicheng" class="zhicheng" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>');
                                    break;
                                }
                            });
                        }else
                        {
                            //$('.scheme-box .body .zhicheng').hide();
                            //未选中
                            //删除表头
                            $('.scheme-box .body table thead tr th[class="zhicheng"]').remove();
                            //获取包含td职称的tr
                            $('.scheme-box .body table tbody td[data-type="zhicheng"]').each(function(index){
                                //获取当前所在tbody
                                let theTbody = $(this).closest('tbody');
                                //获取当前td中rowspan数量
                                let theTdRowspan = $(this).attr('rowspan') || 1;
                                //获取当前所在的行
                                var theTr = $(this).closest('tr');
                                //获取当前tr中的key
                                let key = theTr.data('key');
                                //获取当前所在行下第一下td是什么类型的
                                //二种情况
                                switch(theTr.find('td:eq(0)').data('type'))
                                {
                                    //项目完整行
                                    case 'xiangmu':
                                        //删除当前职称的td并重置后面支付、阶梯式计算的td
                                        $(this).nextAll('td').remove();
                                        $(this).remove();
                                        //判断支付方式是否选中
                                        var pay_type_td = '';
                                        if($('.scheme-box .checkbox input[type="checkbox"][value="3"]').is(':checked') == true)
                                        {
                                            pay_type_td = '<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                            '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                            '<div class="flex-table-div">'+
                                                                '<img class="add-icon" src="/assets/img/add.png" />'+
                                                                '<div class="empty-status">全部</div>'+
                                                                '<div class="item-names" style="display:none;">'+
                                                                '</div>'+
                                                            '</div>'+
                                                        '</td>';
                                        }
                                        theTr.append(pay_type_td+
                                            '<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>');
                                        //刷新样式
                                        $('.selectpicker').selectpicker('refresh');
                                        //删除当前与后续的n个tr总共theTdRowspan个
                                        var remain = theTdRowspan*1-1;
                                        if(remain > 0)
                                        {
                                            //删除剩余的下n行
                                            theTr.nextAll().slice(0, remain).remove();
                                            //并修tr是data-key=x的项目的rowspan-n
                                            theTbody.find('tr[data-key="'+key+'"]').first().find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                                                return (value*1)-(remain*1);
                                            });
                                        }
                                    break;
                                    //追加职称行
                                    case 'zhicheng':
                                        //删除当前与后续的n个tr总共theTdRowspan个
                                        var remain = theTdRowspan*1-1;
                                        if(remain > 0)
                                        {
                                            //删除剩余的下n行
                                            theTr.nextAll().slice(0, remain).remove();
                                        }
                                        theTr.remove();
                                        //并修tr是data-key=x的项目的rowspan-n
                                        theTbody.find('tr[data-key="'+key+'"]').first().find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                                            return (value*1)-(theTdRowspan*1);
                                        });
                                    break;
                                }
                            });
                        }
                    break;
                    //支付方式
                    case '3':
                        //alert('支付方式');
                        if(that.is(':checked') == true)
                        {
                            //选中
                            //追加表头
                            $('.scheme-box .body table thead tr th:last').before('<th style="width:80px;" class="pay_type">支付方式</th>');
                            //获取tr
                            $('.scheme-box .body table tbody tr').each(function(index){
                                //获取当前所在行下第一个td是什么类型
                                var theTr = $(this);
                                //二种情况
                                switch(theTr.find('td:eq(0)').data('type'))
                                {
                                    //项目完整行
                                    case 'xiangmu':
                                    //追加职称行
                                    case 'zhicheng':
                                        //alert('项目完整行');
                                        //追加支付方式
                                        theTr.find('td:last').before('<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>');
                                    break;
                                }
                            });
                        }else
                        {
                            //未选中
                            //删除表头
                            $('.scheme-box .body table thead tr th[class="pay_type"]').remove();
                            //获取包含td支付方式的tr
                            $('.scheme-box .body table tbody td[data-type="pay_type"]').each(function(index){
                                //alert(index);
                                //获取当前所在的行
                                var theTr = $(this).closest('tr');
                                //获取当前所在行下第一下td是什么类型的
                                //三种情况
                                switch(theTr.find('td:eq(0)').data('type'))
                                {
                                    //项目完整行
                                    case 'xiangmu':
                                    //追加职称行
                                    case 'zhicheng':
                                        //删除当前支付的td并重置后面阶梯式计算的td
                                        $(this).nextAll('td').remove();
                                        $(this).remove();
                                        theTr.append('<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>');
                                        //刷新样式
                                        $('.selectpicker').selectpicker('refresh');
                                    break;
                                    //追加支付行
                                    case 'pay_type':
                                        //alert('追加支付行');
                                        //获取到当前行前拆分单元格
                                        mergePreviousCells(theTr, 'zhicheng', -1);
                                        mergePreviousCells(theTr, 'xiangmu', -1);
                                        //删除当前行
                                        theTr.remove();
                                    break;
                                }
                            });
                        }
                    break;
                }
            });
            
            //点击项目弹框
            let allXiangmuArray = [];
            $(document).on('click', '.scheme-box .body .xiangmu .add-icon', function(){
                let that = $(this);
                //alert($(this).closest('tr').index());
                let key = $('.scheme-box .body tbody tr:last').data('key');
                //获取已选项目
                var use_node_obj = get_use_node(that.closest('td'));
                //console.log(use_node_obj);

                Fast.api.open('performance/percom/select_xiangmu?use_node_obj='+encodeURIComponent(JSON.stringify(use_node_obj)), '选择项目', {
                    shadeClose:true,
                    shade:0.5,
                    callback:function(xiangmuArray){
                        //先获取项目列表长度
                        let item_length = that.closest('.xiangmu').find('.item').length;
                        //console.log(xiangmuArray);
                        //return false;
                        allXiangmuArray = allXiangmuArray.concat(xiangmuArray);
                        if(xiangmuArray.length > 0)
                        {
                            let xiangmuStr = '';
                            for(let i = 0; i < xiangmuArray.length; i++)
                            {
                                if(i < 5)
                                {
                                    xiangmuStr += '<div data-id="'+xiangmuArray[i]['id']+'" data-scope="'+xiangmuArray[i]['scope']+'" class="item">'+xiangmuArray[i]['text']+'</div>';
                                }else
                                {
                                    xiangmuStr += '<div data-id="'+xiangmuArray[i]['id']+'" data-scope="'+xiangmuArray[i]['scope']+'" class="item" style="display:none;">'+xiangmuArray[i]['text']+'</div>';
                                }
                            }
                            if(xiangmuArray.length > 5)
                            {
                                xiangmuStr += '...';
                            }

                            that.closest('.xiangmu').find('.item-names').html(xiangmuStr);
                            that.closest('.xiangmu').find('.item-names').show();
                            that.closest('.xiangmu').find('.del-icon').show();
                            that.closest('.xiangmu').find('.empty-status').hide();
                            
                            //追加tr
                            //判断职称与支付是否勾选
                            let zhicheng_html = '';
                            if($('.scheme-box .checkbox input[type="checkbox"][value="2"]').is(':checked') == true)
                            {
                                zhicheng_html = '<td data-type="zhicheng" class="zhicheng" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>';
                            }
                            let pay_type_html = '';
                            if($('.scheme-box .checkbox input[type="checkbox"][value="3"]').is(':checked') == true)
                            {
                                pay_type_html = '<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>';
                            }
                            const newRow = $('<tr data-key="'+(key*1+1)+'">').append(
                                            '<td data-type="xiangmu" class="xiangmu" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>'+
                                            zhicheng_html+
                                            pay_type_html+
                                            '<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>'
                                        );
                            if(item_length == 0)
                            {
                                that.closest('tbody').append(newRow);
                                //刷新样式
                                $('.selectpicker').selectpicker('refresh');
                            }
                        }
                    }
                });
            });
            //点击删项目
            $(document).on('click', '.scheme-box .body .xiangmu .del-icon', function(){
                //获取当前tr中的key
                let that = $(this);
                let key = that.closest('tr').data('key');
                $('.scheme-box .body tbody tr[data-key="'+key+'"]').remove();
            });
            //点击选择职称
            $(document).on('click', '.scheme-box .body .zhicheng .add-icon', function(){
                let that = $(this);
                let key = $(this).closest('tr').data('key');
                //alert(key);
                //获取已选项目
                var use_node_obj = get_use_node(that.closest('td'));
                Fast.api.open('performance/percom/select_zhicheng?use_node_obj='+encodeURIComponent(JSON.stringify(use_node_obj)), '选择职称', {
                    shadeClose:true,
                    shade:0.5,
                    callback:function(zhichengArray){
                        //console.log(zhichengArray);
                        let item_length = that.closest('.zhicheng').find('.item').length;
                        if(zhichengArray.length > 0)
                        {
                            let zhichengStr = '';
                            for(let i = 0; i < zhichengArray.length; i++)
                            {
                                if(i < 5)
                                {
                                    zhichengStr += '<div data-id="'+zhichengArray[i]['id']+'" data-scope="'+zhichengArray[i]['scope']+'" class="item">'+zhichengArray[i]['text']+'</div>';
                                }else
                                {
                                    zhichengStr += '<div data-id="'+zhichengArray[i]['id']+'" data-scope="'+zhichengArray[i]['scope']+'" class="item" style="display:none;">'+zhichengArray[i]['text']+'</div>';
                                }
                            }
                            if(zhichengArray.length > 5)
                            {
                                zhichengStr += '...';
                            }
                            that.closest('.zhicheng').find('.item-names').html(zhichengStr);
                            that.closest('.zhicheng').find('.item-names').show();
                            that.closest('.zhicheng').find('.del-icon').show();
                            that.closest('.zhicheng').find('.empty-status').hide();
                            
                            
                            //追加tr
                            //判断支付是否勾选
                            let pay_type_html = '';
                            if($('.scheme-box .checkbox input[type="checkbox"][value="3"]').is(':checked') == true)
                            {
                                pay_type_html = '<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>';
                            }
                            const newRow = $('<tr data-key="'+key+'">').append(
                                            '<td data-type="zhicheng" class="zhicheng" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>'+
                                            pay_type_html+
                                            '<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>'
                                        );
                            if(item_length == 0)
                            {
                                $('.scheme-box .body tbody tr[data-key="'+key+'"]:last').after(newRow);
                                mergePreviousCells(newRow, 'xiangmu');
                                //刷新样式
                                $('.selectpicker').selectpicker('refresh');
                            }
                        }
                    }
                });
            });
            //删除职称
            $(document).on('click', '.scheme-box .body .zhicheng .del-icon', function(){
                let that = $(this);
                //获取当前所在tbody
                let theTbody = that.closest('tbody');
                //获取当前所在tr
                let theTr = that.closest('tr');
                //获取当前tr中的key
                let key = theTr.data('key');
                //获取当前td中rowspan数量
                let theTdRowspan = that.closest('td').attr('rowspan') || 1;
                //判断当前tr下第一个td的data-type
                switch(theTr.find('td:eq(0)').data('type'))
                {
                    //完整行
                    case 'xiangmu':
                        //复制下n行的三个td替换到当前tr下的倒数3-1的td内容
                        var nextXTr = theTr.nextAll().eq(theTdRowspan*1-1);
                        var nextXTdCount = nextXTr.find('td').length*1;
                        //alert(nextXTdCount);
                        var nextXTrTd = nextXTr.find('td').slice(-nextXTdCount).clone(true);
                        theTr.find('td').slice(-nextXTdCount).each(function(index){
                            $(this).replaceWith(nextXTrTd.eq(index));
                        });
                        //并删除下n行
                        theTr.nextAll().slice(0, theTdRowspan*1).remove();
                        //并修改当前行的项目的rowspan-n
                        theTr.find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                            return (value*1)-(theTdRowspan*1);
                        });
                    break;
                    case 'zhicheng':
                        //alert('职称追加行');
                        //删除当前与后续的n个tr总共theTdRowspan个
                        let remain = theTdRowspan*1-1;
                        if(remain > 0)
                        {
                            //删除剩余的下n行
                            theTr.nextAll().slice(0, remain).remove();
                        }
                        theTr.remove();
                        //并修tr是data-key=x的项目的rowspan-n
                        theTbody.find('tr[data-key="'+key+'"]').first().find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                            return (value*1)-(theTdRowspan*1);
                        });
                    break;
                }

            });
            //点击选择支付方式
            $(document).on('click', '.scheme-box .body .pay_type .add-icon', function(){
                let that = $(this);
                let key = $(this).closest('tr').data('key');
                //alert(key);
                //获取已选项目
                var use_node_obj = get_use_node(that.closest('td'));
                Fast.api.open('performance/percom/select_pay?use_node_obj='+encodeURIComponent(JSON.stringify(use_node_obj)), '选择支付方式', {
                    shadeClose:true,
                    shade:0.5,
                    callback:function(payArray)
                    {
                        //console.log(payArray);
                        let item_length = that.closest('.pay_type').find('.item').length;
                        if(payArray.length > 0)
                        {
                            let payStr = '';
                            for(let i = 0; i < payArray.length; i++)
                            {
                                if(i < 5)
                                {
                                    payStr += '<div data-id="'+payArray[i]['id']+'" data-scope="'+payArray[i]['scope']+'" class="item">'+payArray[i]['text']+'</div>';
                                }else
                                {
                                    payStr += '<div data-id="'+payArray[i]['id']+'" data-scope="'+payArray[i]['scope']+'" class="item" style="display:none;">'+payArray[i]['text']+'</div>';
                                }
                            }
                            if(payArray.length > 5)
                            {
                                payStr += '...';
                            }
                            that.closest('.pay_type').find('.item-names').html(payStr);
                            that.closest('.pay_type').find('.item-names').show();
                            that.closest('.pay_type').find('.del-icon').show();
                            that.closest('.pay_type').find('.empty-status').hide();
                            
                            
                            //追加tr
                            const newRow = $('<tr data-key="'+key+'">').append(
                                            '<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>'+
                                            '<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>'
                                        );
                            if(item_length == 0)
                            {
                                that.closest('tr').after(newRow);
                                mergePreviousCells(newRow, 'zhicheng');
                                mergePreviousCells(newRow, 'xiangmu');
                                //刷新样式
                                $('.selectpicker').selectpicker('refresh');
                            }
                        }
                    }
                });
            });
            //删除支付方式
            $(document).on('click', '.scheme-box .body .pay_type .del-icon', function(){
                let that = $(this);
                //获取当前所在tr
                let theTr = that.closest('tr');
                //判断当前tr下第一个td的data-type
                switch(theTr.find('td:eq(0)').data('type'))
                {
                    //完整行
                    case 'xiangmu':
                        //alert('完整');
                        //获取当前tr所在的index
                        var theTrIndex = theTr.index();
                        //复制下一行的两个td替换到当前tr下的倒数2-1的td内容
                        var nextTr = that.closest('tbody').find('tr:eq('+(theTrIndex+1)+')');
                        var nextTrTd = nextTr.find('td').slice(-2).clone(true);
                        theTr.find('td').slice(-2).each(function(index){
                            $(this).replaceWith(nextTrTd.eq(index));
                        });
                        //并删除下一行
                        nextTr.remove();
                        //并修改当前行的项目与职称的rowspan-1
                        theTr.find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                            return value*1-1;
                        });
                        theTr.find('td[data-type="zhicheng"]').attr('rowspan', function(index, value){
                            return value*1-1;
                        });
                    break;
                    //不完整(少项目)
                    case 'zhicheng':
                        //alert('不完整少项目');
                        //获取当前tr所在的index
                        var theTrIndex = theTr.index();
                        //复制下一行的两个td替换到当前tr下的倒数2-1的td内容
                        var nextTr = that.closest('tbody').find('tr:eq('+(theTrIndex+1)+')');
                        var nextTrTd = nextTr.find('td').slice(-2).clone(true);
                        theTr.find('td').slice(-2).each(function(index){
                            $(this).replaceWith(nextTrTd.eq(index));
                        });
                        mergePreviousCells(nextTr, 'zhicheng', -1);
                        mergePreviousCells(nextTr, 'xiangmu', -1);
                        //并删除下一行
                        nextTr.remove();
                    break;
                    //不完整(少项目、职称)
                    case 'pay_type':
                        //alert('不完整');
                        //获取到当前行前拆分单元格
                        mergePreviousCells(theTr, 'zhicheng', -1);
                        mergePreviousCells(theTr, 'xiangmu', -1);
                        //删除当前行
                        theTr.remove();
                    break;
                }
            });
            //监听阶梯式计算下拉
            $(document).on('change', '.scheme-box .body table tbody tr td select.selectpicker', function(){
                let that = $(this);
                switch(that.val())
                {
                    //固定
                    case '1':
                        that.closest('td').find('.unit').text('元');
                        that.closest('td').find('.unit').after('<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>');
                    break;
                    //比例
                    case '2':
                        that.closest('td').find('.unit').text('%');
                        that.closest('td').find('label').remove();
                    break;
                }
            });
            //点击保存按钮
            $('.save-btn').click(function(){
                let condition = {
                    where:[],
                    all_data:[]
                };
                //筛选条件
                $('.scheme-box .condition input[type="checkbox"]').each(function(){
                    if($(this).is(':checked'))
                    {
                        condition.where.push($(this).val());
                    }
                });
                //具体数据
                var all_data = [];
                $('.scheme-box table tbody tr').each(function(tr_index){
                    var thisTr = $(this);
                    var key = thisTr.data('key');
                    //处理当前tr下的td
                    var list = {
                        "key":key,
                        "data":[]
                    };
                    thisTr.find('td').each(function(td_index){
                        var thisTd = $(this);
                        if(thisTd.data('type'))
                        {
                            //存在
                            switch(thisTd.data('type'))
                            {
                                //项目
                                case 'xiangmu':
                                    var tdArray = {
                                        "type":"xiangmu",
                                        "rowspan":thisTd.attr('rowspan') || 1,
                                        "item":[]
                                    };
                                    //获取item长度
                                    var itemObj = thisTd.find('.item');
                                    if(itemObj.length > 0)
                                    {
                                        //存在
                                        itemObj.each(function(){
                                            tdArray.item.push({
                                                'id':$(this).data('id'),
                                                'name':$(this).text(),
                                                'scope':$(this).data('scope')
                                            });
                                        });
                                    }else
                                    {
                                        //不存在
                                    }
                                    list.data.push(tdArray);
                                break;
                                //职称
                                case 'zhicheng':
                                    var tdArray = {
                                        "type":"zhicheng",
                                        "rowspan":thisTd.attr('rowspan') || 1,
                                        "item":[]
                                    };
                                    //获取item长度
                                    var itemObj = thisTd.find('.item');
                                    if(itemObj.length > 0)
                                    {
                                        //存在
                                        itemObj.each(function(){
                                            tdArray.item.push({
                                                'id':$(this).data('id'),
                                                'name':$(this).text(),
                                                'scope':$(this).data('scope')
                                            });
                                        });
                                    }else
                                    {
                                        //不存在
                                    }
                                    list.data.push(tdArray);
                                break;
                                //支付方式
                                case 'pay_type':
                                    var tdArray = {
                                        "type":"pay_type",
                                        "rowspan":thisTd.attr('rowspan') || 1,
                                        "item":[]
                                    };
                                    //获取item长度
                                    var itemObj = thisTd.find('.item');
                                    if(itemObj.length > 0)
                                    {
                                        //存在
                                        itemObj.each(function(){
                                            tdArray.item.push({
                                                'id':$(this).data('id'),
                                                'name':$(this).text(),
                                                'scope':$(this).data('scope')
                                            });
                                        });
                                    }else
                                    {
                                        //不存在
                                    }
                                    list.data.push(tdArray);
                                break;
                            }
                        }else
                        {
                            //不存在
                            var rule_type = thisTd.find("select option:selected").val();
                            var tdArray = {
                                "type":"rule",
                                "rowspan":thisTd.attr('rowspan') || 1,
                                "item":[{
                                    "rule_type":rule_type,
                                    "value":thisTd.find('input[type="number"]').val(),
                                    "is_duo_fen":rule_type == 1 ? (thisTd.find('input[type="checkbox"]:checked').val()*1 || 0) : 0
                                }]
                            };
                            list.data.push(tdArray);
                        }
                    });
                    all_data[tr_index] = list;
                });
                condition['all_data'] = all_data;
                //console.log(condition);
                $('form').find('textarea').val(JSON.stringify(condition));
                $('form').submit();
            });
            // 合并单元格函数
            function mergePreviousCells(targetRow, type, add_minus = 1) {
                const rows = $('.scheme-box .body tbody tr');
                const targetIndex = rows.index(targetRow);
                let targetCell = null;
                // 向上查找最近的指定类型单元格
                for (let i = targetIndex - 1; i >= 0; i--) {
                    const candidate = rows.eq(i).find(`td[data-type="${type}"]:first`);
                    if (candidate.length > 0) {
                        targetCell = candidate;
                        break;
                    }
                }
                if (targetCell) {
                    const currentSpan = parseInt(targetCell.attr('rowspan')) || 1;
                    if(add_minus == 1)
                    {
                        targetCell.attr('rowspan', currentSpan + 1);
                    }else
                    {
                        if(currentSpan > 1)
                        {
                            targetCell.attr('rowspan', currentSpan - 1);
                        }
                    }
                }
            }

            //已选节点
            function get_use_node(objTd){
                //我选的节点id
                var my_node_ids = [];
                //其他的节点id
                var other_node_ids = [];
                //objTd点击当前元素所在的td
                //获取当前所在的tr
                var theTr = objTd.closest('tr');
                var key = theTr.data('key');
                //根据当前类型判断具体业务
                switch(objTd.data('type'))
                {
                    //项目
                    case 'xiangmu':
                        //遍历我选的节点id
                        objTd.find('.item').each(function(){
                            my_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                        });
                        //遍历除了我其他tr下所选的项目节点
                        $('.scheme-box table tbody tr').not(theTr).each(function(){
                            var trThis = $(this);
                            trThis.find('td[data-type="xiangmu"] .item').each(function(){
                                other_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                            });
                        });
                    break;
                    //职称
                    case 'zhicheng':
                        //遍历我选反节点id
                        objTd.find('.item').each(function(){
                            my_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                        });
                        //遍历当前key除了我其他tr下所选职称节点
                        $('.scheme-box table tbody tr[data-key="'+key+'"]').not(theTr).each(function(){
                            var trThis = $(this);
                            trThis.find('td[data-type="zhicheng"] .item').each(function(){
                                other_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                            });
                        });
                    break;
                    //支付方式
                    case 'pay_type':
                        //alert('支付');
                        //遍历我选择的节点id
                        objTd.find('.item').each(function(){
                            my_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                        });
                        //遍历当前key除了我其他tr下所选支付节点
                        //当前tr下td所在第几位
                        //获取上一个td
                        var frontTr = null;
                        if(theTr.find('td').index(objTd) == 0)
                        {
                            //第一位向上查找最近的不是第一位前面的td
                            frontTr = theTr.prevAll('tr').filter(function(){
                                return $(this).find('td:first').data('type') !== 'pay_type';
                            }).first();
                        }else
                        {
                            //不是第一位获取前面的td
                            frontTr = theTr;
                        }
                        //alert($('.body tbody tr').index(frontTr));
                        var prevTd = frontTr.find('td[data-type="pay_type"]').prev('td');
                        var prevTdRowspan = (prevTd.attr('rowspan')*1) || 1;
                        if(prevTdRowspan > 1)
                        {
                            //获取frontTr在tbody中的位置
                            var frontTrIndex = $('.scheme-box table tbody tr').index(frontTr);
                            $('.scheme-box table tbody tr[data-key="'+key+'"]').slice(frontTrIndex, prevTdRowspan+frontTrIndex).not(theTr).each(function(){
                                var trThis = $(this);
                                trThis.find('td[data-type="pay_type"] .item').each(function(){
                                    other_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                                });
                            });
                        }
                    break;
                }
                //console.log(my_node_ids);
                //console.log(other_node_ids);
                return {
                    my_node_ids:my_node_ids,
                    other_node_ids:other_node_ids
                };
            }


            let addNum = 0
            $('.interzone-btn').click(function () {
                addNum++
                if ($('.way-max-money').last().val() == '' || $('.way-min-money').last().val() == '') return layer.msg('范围区间不能为空')
                $('.interzone-box').append(
                    ` <div class="way-box">
                            <div>累计业绩达标: </div>
                            <div class="radius">
                                <input class="form-control way-min-money" value="${$('.way-max-money').last().val()}" data-rule="required" style="width: 80px;"
                                    name="row[ladder][${addNum}][startamount]" type="number">
                                <span>至</span>
                                <input class="form-control way-max-money" data-rule="required" style="width: 80px;"
                                    name="row[ladder][${addNum}][endamount]" type="number">
                            </div>
                            <div>提成</div>
                            <div class="scale">
                                <select style="width: 100px;" class="form-control selectpicker select-change"
                                    name="row[ladder][${addNum}][type]">
                                    <option value="0">按百分比</option>
                                    <option value="1">按固定金额</option>
                                </select>
                            </div>
                            <div>
                                <div class="scale-ipt">
                                    <input class="form-control" data-rule="required" style="width: 100px;"
                                    name="row[ladder][${addNum}][typesum]" type="number">
                                    <span>%</span>
                                </div>
                                
                            </div>
                        </div>`
                )
            })
        },
        select_xiangmu: function(){
            //alert($.jstree.version);
            //alert(xiangmu_json);
            $('#treeview').jstree(JSON.parse(xiangmu_json));
            //保存选择项目
            $('.xiangmu_save').click(function(){
                //alert('ddd');
                // 获取所有选中的节点
                var selectedNodes = $('#treeview').jstree(true).get_selected();
                var xiangmuArray = [];
                // 遍历所有选中的节点
                selectedNodes.forEach(function(nodeId) {
                    var node = $('#treeview').jstree(true).get_node(nodeId);
                    //console.log(node);
                    if(node.children.length == 0 && node.state.disabled == false)
                    {
                        xiangmuArray.push({
                            'id':node.original.old_id,
                            'text':node.text,
                            'scope':node.original.scope
                        });
                    }
                });
                Fast.api.close(xiangmuArray);
            });
        },
        select_zhicheng: function(){
            $('#treeview').jstree(JSON.parse(zhicheng_json));
            $('.zhicheng_save').click(function(){
                var selectedNodes = $('#treeview').jstree(true).get_selected();
                var zhichengArray = [];
                selectedNodes.forEach(function(nodeId) {
                    var node = $('#treeview').jstree(true).get_node(nodeId);
                    if(node.children.length == 0 && node.state.disabled == false)
                    {
                        //console.log(node);
                        zhichengArray.push({
                            'id':node.original.old_id,
                            'text':node.text,
                            'scope':node.original.scope
                        });
                    }
                });
                Fast.api.close(zhichengArray);
            });
        },
        select_pay: function(){
            $('#treeview').jstree(JSON.parse(pay_json));
            $('.pay_save').click(function(){
                var selectedNodes = $('#treeview').jstree(true).get_selected();
                var payArray = [];
                selectedNodes.forEach(function(nodeId) {
                    var node = $('#treeview').jstree(true).get_node(nodeId);
                    if(node.children.length == 0 && node.state.disabled == false){
                        payArray.push({
                            'id':node.original.old_id,
                            'text':node.text,
                            'scope':node.original.scope
                        });
                    }
                });
                Fast.api.close(payArray);
            });
        },
        
        edit: function () {
            $('.next-btn').click(function () {
                if ($('#c-name').val() == '') {
                    return layer.msg('请输入方案名称')
                }
                $('.basic-box').hide()
                $('.yuan-box').eq(1).addClass('yuan-active')
                $('.heng').addClass('heng-active')
                $('.scheme-box').show()
            });
            //提成条件筛选
            $('.scheme-box .checkbox input[type="checkbox"]').click(function(){
                let that = $(this);
                switch(that.val())
                {
                    //职称
                    case '2':
                        if(that.is(':checked') == true)
                        {
                            //$('.scheme-box .body .zhicheng').show();
                            //选中
                            //追加表头
                            $('.scheme-box .body table thead tr th:eq(0)').after('<th style="width:80px;" class="zhicheng">员工职称</th>');
                            //获取tr
                            $('.scheme-box .body table tbody tr').each(function(index){
                                //获取当前所在行下第一个td是什么类型
                                var theTr = $(this);
                                switch(theTr.find('td:eq(0)').data('type'))
                                {
                                    //项目完整行
                                    case 'xiangmu':
                                        theTr.find('td:eq(0)').after('<td data-type="zhicheng" class="zhicheng" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>');
                                    break;
                                }
                            });
                        }else
                        {
                            //$('.scheme-box .body .zhicheng').hide();
                            //未选中
                            //删除表头
                            $('.scheme-box .body table thead tr th[class="zhicheng"]').remove();
                            //获取包含td职称的tr
                            $('.scheme-box .body table tbody td[data-type="zhicheng"]').each(function(index){
                                //获取当前所在tbody
                                let theTbody = $(this).closest('tbody');
                                //获取当前td中rowspan数量
                                let theTdRowspan = $(this).attr('rowspan') || 1;
                                //获取当前所在的行
                                var theTr = $(this).closest('tr');
                                //获取当前tr中的key
                                let key = theTr.data('key');
                                //获取当前所在行下第一下td是什么类型的
                                //二种情况
                                switch(theTr.find('td:eq(0)').data('type'))
                                {
                                    //项目完整行
                                    case 'xiangmu':
                                        //删除当前职称的td并重置后面支付、阶梯式计算的td
                                        $(this).nextAll('td').remove();
                                        $(this).remove();
                                        //判断支付方式是否选中
                                        var pay_type_td = '';
                                        if($('.scheme-box .checkbox input[type="checkbox"][value="3"]').is(':checked') == true)
                                        {
                                            pay_type_td = '<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                            '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                            '<div class="flex-table-div">'+
                                                                '<img class="add-icon" src="/assets/img/add.png" />'+
                                                                '<div class="empty-status">全部</div>'+
                                                                '<div class="item-names" style="display:none;">'+
                                                                '</div>'+
                                                            '</div>'+
                                                        '</td>';
                                        }
                                        theTr.append(pay_type_td+
                                            '<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>');
                                        //刷新样式
                                        $('.selectpicker').selectpicker('refresh');
                                        //删除当前与后续的n个tr总共theTdRowspan个
                                        var remain = theTdRowspan*1-1;
                                        if(remain > 0)
                                        {
                                            //删除剩余的下n行
                                            theTr.nextAll().slice(0, remain).remove();
                                            //并修tr是data-key=x的项目的rowspan-n
                                            theTbody.find('tr[data-key="'+key+'"]').first().find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                                                return (value*1)-(remain*1);
                                            });
                                        }
                                    break;
                                    //追加职称行
                                    case 'zhicheng':
                                        //删除当前与后续的n个tr总共theTdRowspan个
                                        var remain = theTdRowspan*1-1;
                                        if(remain > 0)
                                        {
                                            //删除剩余的下n行
                                            theTr.nextAll().slice(0, remain).remove();
                                        }
                                        theTr.remove();
                                        //并修tr是data-key=x的项目的rowspan-n
                                        theTbody.find('tr[data-key="'+key+'"]').first().find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                                            return (value*1)-(theTdRowspan*1);
                                        });
                                    break;
                                }
                            });
                        }
                    break;
                    //支付方式
                    case '3':
                        //alert('支付方式');
                        if(that.is(':checked') == true)
                        {
                            //选中
                            //追加表头
                            $('.scheme-box .body table thead tr th:last').before('<th style="width:80px;" class="pay_type">支付方式</th>');
                            //获取tr
                            $('.scheme-box .body table tbody tr').each(function(index){
                                //获取当前所在行下第一个td是什么类型
                                var theTr = $(this);
                                //二种情况
                                switch(theTr.find('td:eq(0)').data('type'))
                                {
                                    //项目完整行
                                    case 'xiangmu':
                                    //追加职称行
                                    case 'zhicheng':
                                        //alert('项目完整行');
                                        //追加支付方式
                                        theTr.find('td:last').before('<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>');
                                    break;
                                }
                            });
                        }else
                        {
                            //未选中
                            //删除表头
                            $('.scheme-box .body table thead tr th[class="pay_type"]').remove();
                            //获取包含td支付方式的tr
                            $('.scheme-box .body table tbody td[data-type="pay_type"]').each(function(index){
                                //alert(index);
                                //获取当前所在的行
                                var theTr = $(this).closest('tr');
                                //获取当前所在行下第一下td是什么类型的
                                //三种情况
                                switch(theTr.find('td:eq(0)').data('type'))
                                {
                                    //项目完整行
                                    case 'xiangmu':
                                    //追加职称行
                                    case 'zhicheng':
                                        //删除当前支付的td并重置后面阶梯式计算的td
                                        $(this).nextAll('td').remove();
                                        $(this).remove();
                                        theTr.append('<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>');
                                        //刷新样式
                                        $('.selectpicker').selectpicker('refresh');
                                    break;
                                    //追加支付行
                                    case 'pay_type':
                                        //alert('追加支付行');
                                        //获取到当前行前拆分单元格
                                        mergePreviousCells(theTr, 'zhicheng', -1);
                                        mergePreviousCells(theTr, 'xiangmu', -1);
                                        //删除当前行
                                        theTr.remove();
                                    break;
                                }
                            });
                        }
                    break;
                }
            });
            //点击项目弹框
            let allXiangmuArray = [];
            $(document).on('click', '.scheme-box .body .xiangmu .add-icon', function(){
                let that = $(this);
                //alert($(this).closest('tr').index());
                let key = $('.scheme-box .body tbody tr:last').data('key');
                //获取已选项目
                var use_node_obj = get_use_node(that.closest('td'));

                Fast.api.open('performance/percom/select_xiangmu?use_node_obj='+encodeURIComponent(JSON.stringify(use_node_obj)), '选择项目', {
                    shadeClose:true,
                    shade:0.5,
                    callback:function(xiangmuArray){
                        //先获取项目列表长度
                        let item_length = that.closest('.xiangmu').find('.item').length;
                        //console.log(xiangmuArray);
                        //return false;
                        allXiangmuArray = allXiangmuArray.concat(xiangmuArray);
                        if(xiangmuArray.length > 0)
                        {
                            let xiangmuStr = '';
                            for(let i = 0; i < xiangmuArray.length; i++)
                            {
                                if(i < 5)
                                {
                                    xiangmuStr += '<div data-id="'+xiangmuArray[i]['id']+'" data-scope="'+xiangmuArray[i]['scope']+'" class="item">'+xiangmuArray[i]['text']+'</div>';
                                }else
                                {
                                    xiangmuStr += '<div data-id="'+xiangmuArray[i]['id']+'" data-scope="'+xiangmuArray[i]['scope']+'" class="item" style="display:none;">'+xiangmuArray[i]['text']+'</div>';
                                }
                            }
                            if(xiangmuArray.length > 5)
                            {
                                xiangmuStr += '...';
                            }

                            that.closest('.xiangmu').find('.item-names').html(xiangmuStr);
                            that.closest('.xiangmu').find('.item-names').show();
                            that.closest('.xiangmu').find('.del-icon').show();
                            that.closest('.xiangmu').find('.empty-status').hide();
                            
                            //追加tr
                            //判断职称与支付是否勾选
                            let zhicheng_html = '';
                            if($('.scheme-box .checkbox input[type="checkbox"][value="2"]').is(':checked') == true)
                            {
                                zhicheng_html = '<td data-type="zhicheng" class="zhicheng" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>';
                            }
                            let pay_type_html = '';
                            if($('.scheme-box .checkbox input[type="checkbox"][value="3"]').is(':checked') == true)
                            {
                                pay_type_html = '<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>';
                            }
                            const newRow = $('<tr data-key="'+(key*1+1)+'">').append(
                                            '<td data-type="xiangmu" class="xiangmu" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>'+
                                            zhicheng_html+
                                            pay_type_html+
                                            '<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>'
                                        );
                            if(item_length == 0)
                            {
                                that.closest('tbody').append(newRow);
                                //刷新样式
                                $('.selectpicker').selectpicker('refresh');
                            }
                        }
                    }
                });
            });
            //点击删项目
            $(document).on('click', '.scheme-box .body .xiangmu .del-icon', function(){
                //获取当前tr中的key
                let that = $(this);
                let key = that.closest('tr').data('key');
                $('.scheme-box .body tbody tr[data-key="'+key+'"]').remove();
            });
            //点击选择职称
            $(document).on('click', '.scheme-box .body .zhicheng .add-icon', function(){
                let that = $(this);
                let key = $(this).closest('tr').data('key');
                //获取已选项目
                var use_node_obj = get_use_node(that.closest('td'));
                //alert(key);
                Fast.api.open('performance/percom/select_zhicheng?use_node_obj='+encodeURIComponent(JSON.stringify(use_node_obj)), '选择职称', {
                    shadeClose:true,
                    shade:0.5,
                    callback:function(zhichengArray){
                        //console.log(zhichengArray);
                        let item_length = that.closest('.zhicheng').find('.item').length;
                        if(zhichengArray.length > 0)
                        {
                            let zhichengStr = '';
                            for(let i = 0; i < zhichengArray.length; i++)
                            {
                                if(i < 5)
                                {
                                    zhichengStr += '<div data-id="'+zhichengArray[i]['id']+'" data-scope="'+zhichengArray[i]['scope']+'" class="item">'+zhichengArray[i]['text']+'</div>';
                                }else
                                {
                                    zhichengStr += '<div data-id="'+zhichengArray[i]['id']+'" data-scope="'+zhichengArray[i]['scope']+'" class="item" style="display:none;">'+zhichengArray[i]['text']+'</div>';
                                }
                            }
                            if(zhichengArray.length > 5)
                            {
                                zhichengStr += '...';
                            }
                            that.closest('.zhicheng').find('.item-names').html(zhichengStr);
                            that.closest('.zhicheng').find('.item-names').show();
                            that.closest('.zhicheng').find('.del-icon').show();
                            that.closest('.zhicheng').find('.empty-status').hide();
                            
                            
                            //追加tr
                            //判断支付是否勾选
                            let pay_type_html = '';
                            if($('.scheme-box .checkbox input[type="checkbox"][value="3"]').is(':checked') == true)
                            {
                                pay_type_html = '<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>';
                            }
                            const newRow = $('<tr data-key="'+key+'">').append(
                                            '<td data-type="zhicheng" class="zhicheng" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>'+
                                            pay_type_html+
                                            '<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>'
                                        );
                            if(item_length == 0)
                            {
                                $('.scheme-box .body tbody tr[data-key="'+key+'"]:last').after(newRow);
                                mergePreviousCells(newRow, 'xiangmu');
                                //刷新样式
                                $('.selectpicker').selectpicker('refresh');
                            }
                        }
                    }
                });
            });
            //删除职称
            $(document).on('click', '.scheme-box .body .zhicheng .del-icon', function(){
                let that = $(this);
                //获取当前所在tbody
                let theTbody = that.closest('tbody');
                //获取当前所在tr
                let theTr = that.closest('tr');
                //获取当前tr中的key
                let key = theTr.data('key');
                //获取当前td中rowspan数量
                let theTdRowspan = that.closest('td').attr('rowspan') || 1;
                //判断当前tr下第一个td的data-type
                switch(theTr.find('td:eq(0)').data('type'))
                {
                    //完整行
                    case 'xiangmu':
                        //复制下n行的三个td替换到当前tr下的倒数3-1的td内容
                        var nextXTr = theTr.nextAll().eq(theTdRowspan*1-1);
                        var nextXTdCount = nextXTr.find('td').length*1;
                        //alert(nextXTdCount);
                        var nextXTrTd = nextXTr.find('td').slice(-nextXTdCount).clone(true);
                        theTr.find('td').slice(-nextXTdCount).each(function(index){
                            $(this).replaceWith(nextXTrTd.eq(index));
                        });
                        //并删除下n行
                        theTr.nextAll().slice(0, theTdRowspan*1).remove();
                        //并修改当前行的项目的rowspan-n
                        theTr.find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                            return (value*1)-(theTdRowspan*1);
                        });
                    break;
                    case 'zhicheng':
                        //alert('职称追加行');
                        //删除当前与后续的n个tr总共theTdRowspan个
                        let remain = theTdRowspan*1-1;
                        if(remain > 0)
                        {
                            //删除剩余的下n行
                            theTr.nextAll().slice(0, remain).remove();
                        }
                        theTr.remove();
                        //并修tr是data-key=x的项目的rowspan-n
                        theTbody.find('tr[data-key="'+key+'"]').first().find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                            return (value*1)-(theTdRowspan*1);
                        });
                    break;
                }

            });
            //点击选择支付方式
            $(document).on('click', '.scheme-box .body .pay_type .add-icon', function(){
                let that = $(this);
                let key = $(this).closest('tr').data('key');
                //alert(key);
                //获取已选项目
                var use_node_obj = get_use_node(that.closest('td'));
                Fast.api.open('performance/percom/select_pay?use_node_obj='+encodeURIComponent(JSON.stringify(use_node_obj)), '选择支付方式', {
                    shadeClose:true,
                    shade:0.5,
                    callback:function(payArray)
                    {
                        //console.log(payArray);
                        let item_length = that.closest('.pay_type').find('.item').length;
                        if(payArray.length > 0)
                        {
                            let payStr = '';
                            for(let i = 0; i < payArray.length; i++)
                            {
                                if(i < 5)
                                {
                                    payStr += '<div data-id="'+payArray[i]['id']+'" data-scope="'+payArray[i]['scope']+'" class="item">'+payArray[i]['text']+'</div>';
                                }else
                                {
                                    payStr += '<div data-id="'+payArray[i]['id']+'" data-scope="'+payArray[i]['scope']+'" class="item" style="display:none;">'+payArray[i]['text']+'</div>';
                                }
                            }
                            if(payArray.length > 5)
                            {
                                payStr += '...';
                            }
                            that.closest('.pay_type').find('.item-names').html(payStr);
                            that.closest('.pay_type').find('.item-names').show();
                            that.closest('.pay_type').find('.del-icon').show();
                            that.closest('.pay_type').find('.empty-status').hide();
                            
                            
                            //追加tr
                            const newRow = $('<tr data-key="'+key+'">').append(
                                            '<td data-type="pay_type" class="pay_type" style="width:80px;">'+
                                                '<img style="display:none;" class="del-icon" src="/assets/img/del.png">'+
                                                '<div class="flex-table-div">'+
                                                    '<img class="add-icon" src="/assets/img/add.png" />'+
                                                    '<div class="empty-status">全部</div>'+
                                                    '<div class="item-names" style="display:none;">'+
                                                    '</div>'+
                                                '</div>'+
                                            '</td>'+
                                            '<td style="width:176px;">'+
                                                '<div class="flex-table-div">'+
                                                    '<div>'+
                                                        '<select class="form-control selectpicker">'+
                                                            '<option value="1">固定</option>'+
                                                            '<option value="2">比例</option>'+
                                                        '</select>'+
                                                    '</div>'+
                                                    '<input style="width:70px" class="form-control" type="number" name="" min="0" step="1" />'+
                                                    '<span class="unit">元</span>'+
                                                    '<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>'+
                                                '</div>'+
                                            '</td>'
                                        );
                            if(item_length == 0)
                            {
                                that.closest('tr').after(newRow);
                                mergePreviousCells(newRow, 'zhicheng');
                                mergePreviousCells(newRow, 'xiangmu');
                                //刷新样式
                                $('.selectpicker').selectpicker('refresh');
                            }
                        }
                    }
                });
            });
            //删除支付方式
            $(document).on('click', '.scheme-box .body .pay_type .del-icon', function(){
                let that = $(this);
                //获取当前所在tr
                let theTr = that.closest('tr');
                //判断当前tr下第一个td的data-type
                switch(theTr.find('td:eq(0)').data('type'))
                {
                    //完整行
                    case 'xiangmu':
                        //alert('完整');
                        //获取当前tr所在的index
                        var theTrIndex = theTr.index();
                        //复制下一行的两个td替换到当前tr下的倒数2-1的td内容
                        var nextTr = that.closest('tbody').find('tr:eq('+(theTrIndex+1)+')');
                        var nextTrTd = nextTr.find('td').slice(-2).clone(true);
                        theTr.find('td').slice(-2).each(function(index){
                            $(this).replaceWith(nextTrTd.eq(index));
                        });
                        //并删除下一行
                        nextTr.remove();
                        //并修改当前行的项目与职称的rowspan-1
                        theTr.find('td[data-type="xiangmu"]').attr('rowspan', function(index, value){
                            return value*1-1;
                        });
                        theTr.find('td[data-type="zhicheng"]').attr('rowspan', function(index, value){
                            return value*1-1;
                        });
                    break;
                    //不完整(少项目)
                    case 'zhicheng':
                        //alert('不完整少项目');
                        //获取当前tr所在的index
                        var theTrIndex = theTr.index();
                        //复制下一行的两个td替换到当前tr下的倒数2-1的td内容
                        var nextTr = that.closest('tbody').find('tr:eq('+(theTrIndex+1)+')');
                        var nextTrTd = nextTr.find('td').slice(-2).clone(true);
                        theTr.find('td').slice(-2).each(function(index){
                            $(this).replaceWith(nextTrTd.eq(index));
                        });
                        mergePreviousCells(nextTr, 'zhicheng', -1);
                        mergePreviousCells(nextTr, 'xiangmu', -1);
                        //并删除下一行
                        nextTr.remove();
                    break;
                    //不完整(少项目、职称)
                    case 'pay_type':
                        //alert('不完整');
                        //获取到当前行前拆分单元格
                        mergePreviousCells(theTr, 'zhicheng', -1);
                        mergePreviousCells(theTr, 'xiangmu', -1);
                        //删除当前行
                        theTr.remove();
                    break;
                }
            });
            //监听阶梯式计算下拉
            $(document).on('change', '.scheme-box .body table tbody tr td select.selectpicker', function(){
                let that = $(this);
                switch(that.val())
                {
                    //固定
                    case '1':
                        that.closest('td').find('.unit').text('元');
                        that.closest('td').find('.unit').after('<label style="margin-bottom: 0px; margin-left: 10px;"><input type="checkbox" checked value="1"> 多人分配提成</label>');
                    break;
                    //比例
                    case '2':
                        that.closest('td').find('.unit').text('%');
                        that.closest('td').find('label').remove();
                    break;
                }
            });
            //点击保存按钮
            $('.save-btn').click(function(){
                let condition = {
                    where:[],
                    all_data:[]
                };
                //筛选条件
                $('.scheme-box .condition input[type="checkbox"]').each(function(){
                    if($(this).is(':checked'))
                    {
                        condition.where.push($(this).val());
                    }
                });
                //具体数据
                var all_data = [];
                $('.scheme-box table tbody tr').each(function(tr_index){
                    var thisTr = $(this);
                    var key = thisTr.data('key');
                    //处理当前tr下的td
                    var list = {
                        "key":key,
                        "data":[]
                    };
                    thisTr.find('td').each(function(td_index){
                        var thisTd = $(this);
                        if(thisTd.data('type'))
                        {
                            //存在
                            switch(thisTd.data('type'))
                            {
                                //项目
                                case 'xiangmu':
                                    var tdArray = {
                                        "type":"xiangmu",
                                        "rowspan":thisTd.attr('rowspan') || 1,
                                        "item":[]
                                    };
                                    //获取item长度
                                    var itemObj = thisTd.find('.item');
                                    if(itemObj.length > 0)
                                    {
                                        //存在
                                        itemObj.each(function(){
                                            tdArray.item.push({
                                                'id':$(this).data('id'),
                                                'name':$(this).text(),
                                                'scope':$(this).data('scope')
                                            });
                                        });
                                    }else
                                    {
                                        //不存在
                                    }
                                    list.data.push(tdArray);
                                break;
                                //职称
                                case 'zhicheng':
                                    var tdArray = {
                                        "type":"zhicheng",
                                        "rowspan":thisTd.attr('rowspan') || 1,
                                        "item":[]
                                    };
                                    //获取item长度
                                    var itemObj = thisTd.find('.item');
                                    if(itemObj.length > 0)
                                    {
                                        //存在
                                        itemObj.each(function(){
                                            tdArray.item.push({
                                                'id':$(this).data('id'),
                                                'name':$(this).text(),
                                                'scope':$(this).data('scope')
                                            });
                                        });
                                    }else
                                    {
                                        //不存在
                                    }
                                    list.data.push(tdArray);
                                break;
                                //支付方式
                                case 'pay_type':
                                    var tdArray = {
                                        "type":"pay_type",
                                        "rowspan":thisTd.attr('rowspan') || 1,
                                        "item":[]
                                    };
                                    //获取item长度
                                    var itemObj = thisTd.find('.item');
                                    if(itemObj.length > 0)
                                    {
                                        //存在
                                        itemObj.each(function(){
                                            tdArray.item.push({
                                                'id':$(this).data('id'),
                                                'name':$(this).text(),
                                                'scope':$(this).data('scope')
                                            });
                                        });
                                    }else
                                    {
                                        //不存在
                                    }
                                    list.data.push(tdArray);
                                break;
                            }
                        }else
                        {
                            //不存在
                            var rule_type = thisTd.find("select option:selected").val();
                            var tdArray = {
                                "type":"rule",
                                "rowspan":thisTd.attr('rowspan') || 1,
                                "item":[{
                                    "rule_type":rule_type,
                                    "value":thisTd.find('input[type="number"]').val(),
                                    "is_duo_fen":rule_type == 1 ? (thisTd.find('input[type="checkbox"]:checked').val()*1 || 0) : 0
                                }]
                            };
                            list.data.push(tdArray);
                        }
                    });
                    all_data[tr_index] = list;
                });
                condition['all_data'] = all_data;
                //console.log(condition);
                $('form').find('textarea').val(JSON.stringify(condition));
                $('form').submit();
            });
            //已选节点
            function get_use_node(objTd){
                //我选的节点id
                var my_node_ids = [];
                //其他的节点id
                var other_node_ids = [];
                //objTd点击当前元素所在的td
                //获取当前所在的tr
                var theTr = objTd.closest('tr');
                var key = theTr.data('key');
                //根据当前类型判断具体业务
                switch(objTd.data('type'))
                {
                    //项目
                    case 'xiangmu':
                        //遍历我选的节点id
                        objTd.find('.item').each(function(){
                            my_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                        });
                        //遍历除了我其他tr下所选的项目节点
                        $('.scheme-box table tbody tr').not(theTr).each(function(){
                            var trThis = $(this);
                            trThis.find('td[data-type="xiangmu"] .item').each(function(){
                                other_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                            });
                        });
                    break;
                    //职称
                    case 'zhicheng':
                        //遍历我选反节点id
                        objTd.find('.item').each(function(){
                            my_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                        });
                        //遍历当前key除了我其他tr下所选职称节点
                        $('.scheme-box table tbody tr[data-key="'+key+'"]').not(theTr).each(function(){
                            var trThis = $(this);
                            trThis.find('td[data-type="zhicheng"] .item').each(function(){
                                other_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                            });
                        });
                    break;
                    //支付方式
                    case 'pay_type':
                        //alert('支付');
                        //遍历我选择的节点id
                        objTd.find('.item').each(function(){
                            my_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                        });
                        //遍历当前key除了我其他tr下所选支付节点
                        //当前tr下td所在第几位
                        //获取上一个td
                        var frontTr = null;
                        if(theTr.find('td').index(objTd) == 0)
                        {
                            //第一位向上查找最近的不是第一位前面的td
                            frontTr = theTr.prevAll('tr').filter(function(){
                                return $(this).find('td:first').data('type') !== 'pay_type';
                            }).first();
                        }else
                        {
                            //不是第一位获取前面的td
                            frontTr = theTr;
                        }
                        //alert($('.body tbody tr').index(frontTr));
                        var prevTd = frontTr.find('td[data-type="pay_type"]').prev('td');
                        var prevTdRowspan = (prevTd.attr('rowspan')*1) || 1;
                        if(prevTdRowspan > 1)
                        {
                            //获取frontTr在tbody中的位置
                            var frontTrIndex = $('.scheme-box table tbody tr').index(frontTr);
                            $('.scheme-box table tbody tr[data-key="'+key+'"]').slice(frontTrIndex, prevTdRowspan+frontTrIndex).not(theTr).each(function(){
                                var trThis = $(this);
                                trThis.find('td[data-type="pay_type"] .item').each(function(){
                                    other_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                                });
                            });
                        }
                    break;
                }
                //console.log(my_node_ids);
                //console.log(other_node_ids);
                return {
                    my_node_ids:my_node_ids,
                    other_node_ids:other_node_ids
                };
            }
            // 合并单元格函数
            function mergePreviousCells(targetRow, type, add_minus = 1) {
                const rows = $('.scheme-box .body tbody tr');
                const targetIndex = rows.index(targetRow);
                let targetCell = null;
                // 向上查找最近的指定类型单元格
                for (let i = targetIndex - 1; i >= 0; i--) {
                    const candidate = rows.eq(i).find(`td[data-type="${type}"]:first`);
                    if (candidate.length > 0) {
                        targetCell = candidate;
                        break;
                    }
                }
                if (targetCell) {
                    const currentSpan = parseInt(targetCell.attr('rowspan')) || 1;
                    if(add_minus == 1)
                    {
                        targetCell.attr('rowspan', currentSpan + 1);
                    }else
                    {
                        if(currentSpan > 1)
                        {
                            targetCell.attr('rowspan', currentSpan - 1);
                        }
                    }
                }
            }
            Controller.api.bindevent();
        },
        //总部方案
        toppercom:function()
        {
            $(document).on('click', '.percom-shop-type-item', function(){
                location.href = $(this).data('url');
            });
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'performance/percom/toppercom' + location.search,
                    table: 'percom',
                }
            });
            var table = $("#table");
            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                Search: true,
                commonSearch: true,
                searchFormVisible: true,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id'), operate: false },
                        { field: 'name', title: __('Name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'type', title: __('Type'), operate: false, searchList: { "0": __('Type 0'), "1": __('Type 1'), "2": __('Type 2') }, formatter: Table.api.formatter.normal },
                        { field: 'createtime', title: __('Createtime'), operate: false, addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'status', title: __('Status'), searchList: { "0": __('Status 0'), "1": __('Status 1') }, formatter: Table.api.formatter.status, custom:{0:'success', 1:'primary'} },
                        // {field: 'shop_id', title: __('Shop_id')},
                        //{ field: 'staff_ids', title: __('Staff_ids'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        // {field: 'status', title: __('Status'), searchList: {"0":__('Status 0'),"1":__('Status 1')}, formatter: Table.api.formatter.status},
                        // {field: 'gtype', title: __('Gtype'), searchList: {"0":__('Gtype 0'),"1":__('Gtype 1')}, formatter: Table.api.formatter.normal},
                        // {field: 'i1type', title: __('I1type'), searchList: {"0":__('I1type 0'),"1":__('I1type 1')}, formatter: Table.api.formatter.normal},
                        // {field: 'i3type', title: __('I3type'), searchList: {"0":__('I3type 0'),"1":__('I3type 1')}, formatter: Table.api.formatter.normal},
                        // {field: 'sku_ids', title: __('Sku_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'sku1_ids', title: __('Sku1_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'i3typesum', title: __('I3typesum'), operate: 'LIKE'},
                        // {field: 'i1typesum', title: __('I1typesum'), operate: 'LIKE'},
                        // {field: 'gtypesum', title: __('Gtypesum'), operate: 'LIKE'},

                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        //{ field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons :[
                                {
                                    name: 'detail',
                                    text: '详情',
                                    title: '详情',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: "performance/percom/detail",
                                },
                                {
                                    name: 'resubmittoshop',
                                    text: '添加到本店',
                                    title: '添加到本店',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    url: "performance/percom/resubmittoshop",
                                    refresh: true,
                                    hidden:function(row)
                                    {
                                        if(row.already_copy == 1)
                                        {
                                            return true;
                                        }else
                                        {
                                            return false;
                                        }
                                    }
                                }
                            ],
                            callback: function (data) {
                                table.bootstrapTable('refresh', {});
                                return false;
                            },
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        detail:function()
        {
            //alert();
            //点击项目弹框
            let allXiangmuArray = [];
            $(document).on('click', '.scheme-box .body .xiangmu .add-icon', function(){
                let that = $(this);
                //alert($(this).closest('tr').index());
                let key = $('.scheme-box .body tbody tr:last').data('key');
                //获取已选项目
                var use_node_obj = get_use_node(that.closest('td'));

                Fast.api.open('performance/percom/select_xiangmu?use_node_obj='+encodeURIComponent(JSON.stringify(use_node_obj))+'&shop_id='+shop_id, '选择项目', {
                    shadeClose:true,
                    shade:0.5,
                    callback:function(xiangmuArray){
                        
                    }
                });
            });
            //点击选择职称
            $(document).on('click', '.scheme-box .body .zhicheng .add-icon', function(){
                let that = $(this);
                let key = $(this).closest('tr').data('key');
                //获取已选项目
                var use_node_obj = get_use_node(that.closest('td'));
                //alert(key);
                Fast.api.open('performance/percom/select_zhicheng?use_node_obj='+encodeURIComponent(JSON.stringify(use_node_obj))+'&shop_id='+shop_id, '选择职称', {
                    shadeClose:true,
                    shade:0.5,
                    callback:function(zhichengArray){
                        
                    }
                });
            });
            //点击选择支付方式
            $(document).on('click', '.scheme-box .body .pay_type .add-icon', function(){
                let that = $(this);
                let key = $(this).closest('tr').data('key');
                //alert(key);
                //获取已选项目
                var use_node_obj = get_use_node(that.closest('td'));
                Fast.api.open('performance/percom/select_pay?use_node_obj='+encodeURIComponent(JSON.stringify(use_node_obj))+'&shop_id='+shop_id, '选择支付方式', {
                    shadeClose:true,
                    shade:0.5,
                    callback:function(payArray)
                    {
                        
                    }
                });
            });
            //已选节点
            function get_use_node(objTd){
                //我选的节点id
                var my_node_ids = [];
                //其他的节点id
                var other_node_ids = [];
                //objTd点击当前元素所在的td
                //获取当前所在的tr
                var theTr = objTd.closest('tr');
                var key = theTr.data('key');
                //根据当前类型判断具体业务
                switch(objTd.data('type'))
                {
                    //项目
                    case 'xiangmu':
                        //遍历我选的节点id
                        objTd.find('.item').each(function(){
                            my_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                        });
                        //遍历除了我其他tr下所选的项目节点
                        $('.scheme-box table tbody tr').not(theTr).each(function(){
                            var trThis = $(this);
                            trThis.find('td[data-type="xiangmu"] .item').each(function(){
                                other_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                            });
                        });
                    break;
                    //职称
                    case 'zhicheng':
                        //遍历我选反节点id
                        objTd.find('.item').each(function(){
                            my_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                        });
                        //遍历当前key除了我其他tr下所选职称节点
                        $('.scheme-box table tbody tr[data-key="'+key+'"]').not(theTr).each(function(){
                            var trThis = $(this);
                            trThis.find('td[data-type="zhicheng"] .item').each(function(){
                                other_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                            });
                        });
                    break;
                    //支付方式
                    case 'pay_type':
                        //alert('支付');
                        //遍历我选择的节点id
                        objTd.find('.item').each(function(){
                            my_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                        });
                        //遍历当前key除了我其他tr下所选支付节点
                        //当前tr下td所在第几位
                        //获取上一个td
                        var frontTr = null;
                        if(theTr.find('td').index(objTd) == 0)
                        {
                            //第一位向上查找最近的不是第一位前面的td
                            frontTr = theTr.prevAll('tr').filter(function(){
                                return $(this).find('td:first').data('type') !== 'pay_type';
                            }).first();
                        }else
                        {
                            //不是第一位获取前面的td
                            frontTr = theTr;
                        }
                        //alert($('.body tbody tr').index(frontTr));
                        var prevTd = frontTr.find('td[data-type="pay_type"]').prev('td');
                        var prevTdRowspan = (prevTd.attr('rowspan')*1) || 1;
                        if(prevTdRowspan > 1)
                        {
                            //获取frontTr在tbody中的位置
                            var frontTrIndex = $('.scheme-box table tbody tr').index(frontTr);
                            $('.scheme-box table tbody tr[data-key="'+key+'"]').slice(frontTrIndex, prevTdRowspan+frontTrIndex).not(theTr).each(function(){
                                var trThis = $(this);
                                trThis.find('td[data-type="pay_type"] .item').each(function(){
                                    other_node_ids.push($(this).data('scope')+'_'+$(this).data('id'));
                                });
                            });
                        }
                    break;
                }
                //console.log(my_node_ids);
                //console.log(other_node_ids);
                return {
                    my_node_ids:my_node_ids,
                    other_node_ids:other_node_ids
                };
            }
        },
        //方案使用门店
        use_shop:function(){
            var id = Config.id;
            Table.api.init({
                extend:{
                    index_url: 'performance/percom/use_shop?id=' + id +"&"+ location.search,
                }
            });
            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible:false, operate: false},
                        {field: 'code', title: __('店铺编号'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'type', title: __('商家分类'), searchList: {"0":__('直营店'),"1":__('加盟店'),"2":__('社区单店')}, operate: false,formatter: Table.api.formatter.normal},
                        {field: 'shopname', title: __('商家名称'), operate: 'LIKE'},
                        {field: 'person', title: __('联系人'), operate: 'LIKE', operate: false},
                        {field: 'telephone', title: __('联系方式'), operate: 'LIKE', operate: false},
                        {field: 'city', title: __('所属地区'), operate: 'LIKE', operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, operate: false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('营业中'),"hidden":__('下线')}, formatter: Table.api.formatter.status, operate: false}
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        //选择商家
        resubmit:function(){
            var percom_id = Config.percom_id;
            //alert(percom_id);
            //alert('dddd');
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'performance/percom/resubmit?ids=' + percom_id +"&"+ location.search,
                }
            });
            var table = $("#table");
            $(".btn-add").data("area", ["100%", "100%"]);
            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible:false, operate: false},
                        {field: 'code', title: __('店铺编号'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'type', title: __('商家分类'), searchList: {"0":__('直营店'),"1":__('加盟店'),"2":__('社区单店')}, operate: false,formatter: Table.api.formatter.normal},
                        {field: 'shopname', title: __('商家名称'), operate: 'LIKE'},
                        {field: 'person', title: __('联系人'), operate: 'LIKE', operate: false},
                        {field: 'telephone', title: __('联系方式'), operate: 'LIKE', operate: false},
                        {field: 'city', title: __('所属地区'), operate: 'LIKE', operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, operate: false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('营业中'),"hidden":__('下线')}, formatter: Table.api.formatter.status, operate: false}
                    ]
                ]
            });
            $("button[type='submit']").css("background-color","red");
            $("button[type='submit']").css("border-color","red");
            //保存设置
            $(document).on("click", ".choose-shop", function () {
                var ids = Table.api.selectedids(table);
                if (ids.length == 0)
                {
                    layer.msg("请选择要铺设的店铺！");
                    return false;
                }
                Fast.api.ajax({
                    url: 'performance/percom/savepercomshop',
                    type: 'post',
                    loading: false,
                    data: {
                        ids: ids,
                        percom_id: percom_id
                    }
                }, function (data, ret){
                    if (ret.code == 1)
                    {
                        Layer.open({
                            title:'提示',
                            type: 1,
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">'+ret.msg+'</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero)
                            {
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }else
                    {
                        Layer.open({
                            title:'提示',
                            type: 1,
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">操作失败，请稍后重试！</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero)
                            {
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }
                    return false;
                });
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
